<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单编号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入工单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工序编码" prop="processCode">
        <el-input v-model="queryParams.processCode" placeholder="请输入工序编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input v-model="queryParams.equipmentName" placeholder="请输入设备名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.mes_process_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['production:workorderprocess:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['production:workorderprocess:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['production:workorderprocess:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['production:workorderprocess:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workOrderProcessList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="recordId" />
      <el-table-column label="工单编号" align="center" prop="orderCode" />
      <el-table-column label="工序编码" align="center" prop="processCode" />
      <el-table-column label="工序名称" align="center" prop="processName" />
      <el-table-column label="设备名称" align="center" prop="equipmentName" />
      <el-table-column label="操作工姓名" align="center" prop="workerName" />
      <el-table-column label="计划数量" align="center" prop="planQuantity" />
      <el-table-column label="已加工数量" align="center" prop="processedQuantity" />
      <el-table-column label="合格数量" align="center" prop="qualifiedQuantity" />
      <el-table-column label="不合格数量" align="center" prop="unqualifiedQuantity" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_process_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="StartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.StartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['production:workorderprocess:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['production:workorderprocess:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改工单工序记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单" prop="orderId">
              <el-select v-model="form.orderId" placeholder="请选择工单" clearable @change="handleWorkOrderChange" style="width: 100%">
                <el-option
                  v-for="workOrder in workOrderList"
                  :key="workOrder.orderId"
                  :label="`${workOrder.orderCode} - ID:${workOrder.orderId}`"
                  :value="workOrder.orderId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序" prop="processId">
              <el-select v-model="form.processId" placeholder="请选择工序" clearable @change="handleProcessChange" style="width: 100%">
                <el-option
                  v-for="process in processList"
                  :key="process.processId"
                  :label="`${process.processName} - ${process.processCode} - ID:${process.processId}`"
                  :value="process.processId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 设备和操作员信息 -->
        <el-divider content-position="left">设备和操作员信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备" prop="equipmentId">
              <el-select v-model="form.equipmentId" placeholder="请选择设备" clearable @change="handleEquipmentChange" style="width: 100%">
                <el-option
                  v-for="equipment in equipmentList"
                  :key="equipment.equipmentId"
                  :label="`${equipment.equipmentName} - ID:${equipment.equipmentId}`"
                  :value="equipment.equipmentId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作员">
              <el-input :value="`${this.name} - ID:${this.userId}`" readonly disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 数量和时间信息 -->
        <el-divider content-position="left">数量和时间信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划数量" prop="planQuantity">
              <el-input v-model="form.planQuantity" placeholder="请输入计划数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option v-for="dict in dict.type.mes_process_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="StartTime">
              <el-date-picker clearable v-model="form.StartTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开始时间" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="EndTime">
              <el-date-picker clearable v-model="form.EndTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束时间" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWorkOrderProcess, getWorkOrderProcess, delWorkOrderProcess, addWorkOrderProcess, updateWorkOrderProcess } from "@/api/mes/production/workorderprocess";
import { listWorkOrder } from "@/api/mes/production/workorder";
import { listProcess } from "@/api/mes/production/process";
import { listEquipment } from "@/api/mes/equipment/equipment";
import { mapGetters } from 'vuex';

export default {
  name: "WorkOrderProcess",
  dicts: ['mes_process_status'],
  computed: {
    ...mapGetters(['name', 'userId']) // 获取当前登录用户信息
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单工序记录表格数据
      workOrderProcessList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        processCode: null,
        equipmentName: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "工单ID不能为空", trigger: "blur" }
        ],
        processId: [
          { required: true, message: "工序ID不能为空", trigger: "blur" }
        ],
        planQuantity: [
          { required: true, message: "计划数量不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getWorkOrderList();
    this.getProcessList();
    this.getEquipmentList();
  },
  methods: {
    /** 查询工单工序记录列表 */
    getList() {
      this.loading = true;
      listWorkOrderProcess(this.queryParams).then(response => {
        this.workOrderProcessList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        orderId: null,
        orderCode: null,
        processId: null,
        processCode: null,
        processName: null,
        equipmentId: null,
        equipmentName: null,
        workerId: this.userId, // 默认设置为当前登录用户ID
        workerName: this.name, // 默认设置为当前登录用户名称
        planQuantity: null,
        processedQuantity: null,
        qualifiedQuantity: null,
        unqualifiedQuantity: null,
        StartTime: null,
        EndTime: null,
        status: '0'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 默认设置当前登录用户为操作员
      this.form.workerId = this.userId;
      this.form.workerName = this.name;
      this.open = true;
      this.title = "添加工单工序记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recordId = row.recordId || this.ids
      getWorkOrderProcess(recordId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工单工序记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.recordId != null) {
            updateWorkOrderProcess(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWorkOrderProcess(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$modal.confirm('是否确认删除工单工序记录编号为"' + recordIds + '"的数据项？').then(function () {
        return delWorkOrderProcess(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 获取工单列表 */
    getWorkOrderList() {
      listWorkOrder({}).then(response => {
        this.workOrderList = response.rows || [];
      });
    },

    /** 获取工序列表 */
    getProcessList() {
      listProcess({}).then(response => {
        this.processList = response.rows || [];
      });
    },

    /** 获取设备列表 */
    getEquipmentList() {
      listEquipment({}).then(response => {
        this.equipmentList = response.rows || [];
      });
    },

    /** 工单选择变化处理 */
    handleWorkOrderChange(orderId) {
      if (orderId) {
        const selectedWorkOrder = this.workOrderList.find(workOrder => workOrder.orderId === orderId);
        if (selectedWorkOrder) {
          this.form.orderCode = selectedWorkOrder.orderCode;
        }
      } else {
        this.form.orderCode = null;
      }
    },

    /** 工序选择变化处理 */
    handleProcessChange(processId) {
      if (processId) {
        const selectedProcess = this.processList.find(process => process.processId === processId);
        if (selectedProcess) {
          this.form.processCode = selectedProcess.processCode;
          this.form.processName = selectedProcess.processName;
        }
      } else {
        this.form.processCode = null;
        this.form.processName = null;
      }
    },

    /** 设备选择变化处理 */
    handleEquipmentChange(equipmentId) {
      if (equipmentId) {
        const selectedEquipment = this.equipmentList.find(equipment => equipment.equipmentId === equipmentId);
        if (selectedEquipment) {
          this.form.equipmentName = selectedEquipment.equipmentName;
        }
      } else {
        this.form.equipmentName = null;
      }
    }
  },
  /** 导出按钮操作 */
  handleExport() {
    this.download('production/workorderprocess/export', {
      ...this.queryParams
    }, `workorderprocess_${new Date().getTime()}.xlsx`)
  }
};
</script>